package com.yzt.message.msgdialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;

/**
 * desc: 消息悬浮弹出框
 **/
public class MsgFloatDialog extends Dialog {

    private Handler mHandler;

    public MsgFloatDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
    }

    @Override
    public void onStart() {
        super.onStart();
        if (getWindow() != null) {
            // 设置宽度为屏宽, 靠近屏幕底部。
            Window win = getWindow();
            // 一定要设置Background，如果不设置，window属性设置无效
            win.setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
            win.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            WindowManager.LayoutParams params = win.getAttributes();
            params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
            // 使用ViewGroup.LayoutParams，以便Dialog 宽度充满整个屏幕
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            win.setAttributes(params);
        }
        setCanceledOnTouchOutside(false);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new Handler();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                MsgFloatDialog.this.dismiss();
            }
        },MsgFloatDialogHelper.SHOW_DIALOG_TIME);
    }

    @Override
    public void dismiss() {
        try {
            super.dismiss();
            if (mHandler != null) {
                mHandler.removeCallbacksAndMessages(null);
                mHandler = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
